package com.nj.api.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nj.api.entity.Product;
import com.nj.api.mapper.ProductMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    @Resource
    private ProductMapper productMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public Object getRate() {//获取利率
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object rate = valueOperations.get("product:rate");
        if (rate == null){
            QueryWrapper<Product> wrapper = new QueryWrapper<>();
            wrapper.select("avg(rate) as rate");
            Map<String, Object> map = productMapper.selectMaps(wrapper).get(0);
            rate = map.get("rate");
            valueOperations.set("product:rate",rate,2, TimeUnit.HOURS);
        }
        return rate;
    }

    @Override
    //新手宝
    public Product getNew() {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("product_type",0);
        return  productMapper.selectOne(wrapper);
    }

    @Override
    //优选产品
    public List<Product> getYx() {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("product_type",1).and(pro->pro.eq("cycle",1).or().eq("cycle",3).or().eq("cycle",6));
        return productMapper.selectList(wrapper);
    }

    @Override
    //散标产品
    public List<Product>  getSb() {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("product_type",2).orderByDesc("rate").last("limit 3");
        return productMapper.selectList(wrapper);
    }

    @Override
    public List<Product> getByType(String type) {
        QueryWrapper<Product> wrapper = new QueryWrapper<Product>().eq("product_type", type);
        return productMapper.selectList(wrapper);
    }

    @Override
    public List getTop3() {
        return productMapper.getTop3();
    }
}
